package com.chang.multithread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//abc按顺序交替输出多少次 使用await singal方法
@Slf4j
public class abcAwaitSingal extends ReentrantLock {
    private int loopNumber;

    public abcAwaitSingal(int loopNumber) {
        this.loopNumber = loopNumber;
    }
    //打印内容   参数1 输出内容     当前休息室         下一休息室
    public void print(String str,Condition current,Condition next){
        for (int i = 0; i < loopNumber; i++) {
            lock();
            try {
                current.await();
                System.out.print(str);
                next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                unlock();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        abcAwaitSingal awaitSingal=new abcAwaitSingal(5);
        Condition a = awaitSingal.newCondition();
        Condition b = awaitSingal.newCondition();
        Condition c= awaitSingal.newCondition();
        new Thread(()->{
            awaitSingal.print("a", a, b);
        }).start();
        new Thread(()->{
            awaitSingal.print("b", b, c);
        }).start();
        new Thread(()->{
            awaitSingal.print("c", c, a);
        }).start();

        Thread.sleep(500);
        awaitSingal.lock();
        try {
            log.debug("主线程启动了。。。");
            a.signal();
        }finally {
            awaitSingal.unlock();
        }
    }
}

